package ink.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.entity.ProductDevice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IProductDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 机器产品接口
 * @author: 小白白
 * @create: 2021-09-10
 **/

@Api(tags = "机器产品接口")
@RequestMapping("/product")
@RestController
@Slf4j
@CrossOrigin
@ResourcesRoleMapping(resourceName = "基本设置接口", includeRoleNames = MyRole.ADMIN)
public class ProductController {

    @Autowired
    private IProductDeviceService productDeviceService;

    /**
     * 机器列表
     */
    @GetMapping("/list")
    @ApiOperation("获取机器产品列表")
    public ResponseFormat getList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        Page<ProductDevice> page = this.productDeviceService.page(new Page<>(pageNum, pageSize));
        return ResponseFormat.success(page);
    }

    /**
     * 添加机器
     */
    @PostMapping("/add")
    @ApiOperation("添加机器产品")
    public ResponseFormat addProduct(@RequestBody @Validated ProductDevice productDevice) {
        String name = productDevice.getName();
        String type = productDevice.getType();
        QueryWrapper<ProductDevice> q1 = new QueryWrapper<>();
        q1.eq("name", name).or().eq("type", type);
        if (this.productDeviceService.count(q1) != 0) {
            return ResponseFormat.fail("名称和型号不能和已有的重复");
        }
        boolean save = this.productDeviceService.save(productDevice);
        return save ? ResponseFormat.success() : ResponseFormat.fail("添加失败");
    }

    /**
     * 修改机器
     */
    @PutMapping("/update")
    @ApiOperation("修改机器产品")
    public ResponseFormat updateProduct(@RequestBody @Validated ProductDevice productDevice) {
        if (productDevice.getId() == null) {
            return ResponseFormat.fail("请选择Id");
        }
        boolean update = this.productDeviceService.updateById(productDevice);
        return update ? ResponseFormat.success() : ResponseFormat.fail("修改失败");
    }

    /**
     * 删除机器
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除机器")
    public ResponseFormat deleteProduct(@PathVariable("id") Integer id) {
        boolean remove = this.productDeviceService.removeById(id);
        return remove ? ResponseFormat.success() : ResponseFormat.fail("删除失败");
    }

}
